package com.excel.easyExcel.controller;

import com.alibaba.excel.EasyExcel;
import com.excel.easyExcel.service.GoodsService;
import com.excel.easyExcel.vo.ExportVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * @author Xinjie
 * @date 2023/4/25 16:43
 */
@RestController
@RequestMapping("/excel")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @PostMapping("/import")
    public boolean importExcel(@RequestParam(value = "excel") MultipartFile excel) {
        return goodsService.importExcel(excel);
    }

    @SneakyThrows
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(value = "type") String type,
                       @RequestParam(value = "start_date") Long sd,
                       @RequestParam(value = "end_date") Long ed) {
        long l = System.currentTimeMillis();
        setExcelRespProp(response, l + "货物统计", type);
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, ExportVo.class)
                .inMemory(true)
                .sheet(l + "货物统计")
                .doWrite(goodsService.exportExcel(sd, ed));
        outputStream.close();
    }

    private void setExcelRespProp(HttpServletResponse response, String rawFileName, String type) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + "." + type);
    }
}
